<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    //class Users extends CI_Controller
    class Users extends MY_Controller
    {
        private $capdir = "";

        function __construct()
        {
            $this->capdir = dirname(__FILE__)."/../../captcha/";
            $this->_privWhite = array("login");

            parent::__construct();

            $this->load->model("user");
        }

        public function index($flag=1)
        {
			$keyword =  $_POST['keywords']; 
			$where = '';
			if( isset($keyword) ){
				$where = " AND name like '%{$keyword}%' ";
			}

            $this->load->model("group");
            $this->load->model("datacenter");
            $gs = $this->group->getAll2();
            $dcs = $this->datacenter->getAll2();

            $users = $this->user->getAll($flag,$where );
            $this->load->library('pagination');
            $config['base_url'] = site_url().'/users/index/';
            $config['total_rows'] = count($users);
            $config['per_page'] = $this->_pn; 
            $this->pagination->initialize($config); 
            //echo $this->pagination->create_links();exit;

            foreach($users as &$user){
                $user['group'] = $gs[$user['role_id']];
                $user['owner'] = $dcs[$user['datacenter_id']];
                $user['datacenter'] = $dcs[$user['datacenter_id']];
         
				if( $user['sms_warning_level'] )
					$user['receive_sms'] = $this->enum_warning($user['sms_warning_level']);

				if( $user['email_warning_level'] )
					$user['receive_email'] = $this->enum_warning($user['email_warning_level']);


            }
			$data['flag'] = $flag;
            $data['users'] = $users;
            //var_dump($users);exit;
            $this->load->view('template/user/index.html', $data);
        }

		function enum_warning( $num )
		{
			$ret='';
			switch($num){
				case 0:
					$ret = '不接收';
					break;
				case 1:
					$ret = '接收一般警报';
					break;
				case 2:
					$ret = '接收重要警报';
					break;
				case 3:
					$ret = '接收紧急警报';
					break;
				case 4:
					$ret = '接收严重警报';
					break;
			}
			return $ret;
		}

        function my()
        {
            $user = $this->session->userdata['user'];
            $data['gid'] = $user['role_id'];

            $user['owner'] = $user['role_id'];
            $user['gid'] = $user['role_id'];
            $this->load->view('template/user/my.html', $data);
        }


        //产生验证码
        function _scaptcha()
        {
            $this->load->helper('captcha');
            $vals = array(
            //'img_width'=>100,
            'img_height'=>38,
            'img_path'   => $this->capdir,
            'img_url'    => site_url().'/captcha/', //site_url('/captcha/').'/'
            ); 
            $cap = create_captcha($vals); 
            $data = array(
            'captcha_time'  => $cap['time'],
            'ip_address'    => $this->input->ip_address(),
            'word'   => $cap['word']
            ); 
            $query = $this->db->insert_string('captcha', $data);
            $this->db->query($query);

            return $cap;
        }

        //校验验证码
        function _gcaptcha($cap)
        {
            // First, delete old captchas
            $expiration = time()-7200; // Two hour limit
            $this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);  

            // Then see if a captcha exists:
            $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
            $binds = array($cap, $this->input->ip_address(), $expiration);
            $query = $this->db->query($sql, $binds);
            $row = $query->row();

            return $row->count;
        }

        public function login()//装载登录页面vlogin.php
        {
            $msg = "";
            $this->load->helper(array('captcha', 'form','url'));
            $post = $this->input->post();
            if($post){
                if(!$this->_gcaptcha($post['captcha'])){
                    $msg = "验证码错误";
                }
                else{
                    $msg = "验证码错误";
                    $user = $this->user->getUser($post['uemail'], md5($post['upasswd']));
                    if(!$user){
                        $msg = "用户名或密码错误";
                    }
                    elseif($user['ftime']!= '0000-00-00'){
                        $msg = "用户已冻结不能登录";
                    }
					else{
                        $sdata['user'] = $user;
                        $this->session->set_userdata($sdata);

                        //暂时将就兼容旧网页
                        $this->_comptb($user);

                        //redirect('dcim');
                        redirect(site_url("/dcim"));
                    }
                }
            }

            $data['captcha'] = $this->_scaptcha();
            $data['msg'] = $msg;
            $this->load->view('template/user/login.html', $data);

         }

         function _comptb($user)
         {
            session_start();

            $_SESSION['sid'] = $user['id'];
            $_SESSION['role_id'] = $user['role_id'];
            $_SESSION['sname'] = $user['name'];
            $_SESSION['datacenter_id'] = $user['datacenter_id'];
            $_SESSION['owner_id'] = $user['owner_id'];
            $_SESSION['depart_id'] = $user['depart_id'];
			//旧系统
            $_SESSION['aid'] = 9;
            //$_SESSION['sessid'] = md5(time());
			//旧系统是这样的sessid
            $_SESSION['sessid'] = md5($user['mobile'].$user['logid']);
            //var_dump($_SESSION);exit;
         }
         
         function logout()
         {
             $this->session->unset_userdata();
             $this->session->sess_destroy();
             $url = site_url("/users/login");
             //$url = "index.php/users/login";
             echo "<script>parent.location.href='".$url."';</Script>";
         }

         function forgetpwd()
         {
            $this->load->helper('email');

            $email = $this->input->post('email');
            if (valid_email($email)){
                $str = substr(md5(time()),0,6);
                send_email($email, '密码重置', "密码已经重置为$str");
                $this->db->update("sys_staff",array("passwd"=>($str)), array("email"=>$email));
                redirect("/dcim");
            }
            $this->load->view('template/user/forgetpwd.html');

         }

         function add()
         {
            $data = $this->input->post();
            if($data){

                if ($_POST['password'] && !empty($_POST['password']) ) {
                    $data['passwd'] = md5($_POST['password']);
                }else{
                    $str = substr(md5(time()),0,6);
                    $data['passwd'] = md5($str);
                }

                $data['title'] = $data['level'] = $data['role'];

                unset($data['role']);
                unset($data['password']);
                $data['branch_id'] = 0;
                $data['information'] = 0;
                $data['ftime'] = time();
                $data['verify_validity'] = 0;
                $data['verify_code'] = '';
                $data['verify_time'] = 0;
                $data['employment_date'] = date('Y-m-d');

                $data['datacenter_id'] = $this->_user['datacenter_id'];

                $data['owner_id'] = $this->_user['owner_id'];

                $ret = $this->db->insert('sys_staff', $data);
                $userid = $this->db->insert_id();

                $this->logop("sys_staff");

                if ($userid) {
                    $this->allocatePermition($userid, $data['role_id']);
                    $this->setDefaultIcon($userid);//默认图标
                    echo "<script>alert('创建用户成功!');</script>";
                }else{
                    echo "<script>alert('创建用户失败!');</script>";
                }
            }
         }

        //权限编辑操作
        function editPermit($userid)
        {
            $data = $this->input->post();
            $this->load->model("sysrights");

            if($data){
				//var_dump($data);exit;
                $this->logop("sys_staff");
                $this->sysrights->permitModify($userid, $data['data']);
                redirect(site_url("/users/"));
            }
            else{
                $allmenus = $this->sysrights->getAllUserRights($userid);//getrights
                //unset($allmenus[32]);  //配置管理
                //unset($allmenus[166]); //系统配置
                $data['allmenus'] = $allmenus;
                //var_dump( $data['allmenus'] );exit;
				$this->load->view('template/user/role_edit.html',$data);
            }
        }

		//冻结用户,0冻结，1解冻
        function freeze($uid,$flag=0)
		{
			if($this->_user['role_id'] == 4){
               	echo '<meta charset="UTF-8" />';
               	echo "<script>alert('权限不足!');history.go(-1);</script>";
				
			}

			$data['id'] = $uid;
			$data['ftime'] = $flag ? " " : date("Y-m-d");
			//var_dump($data);exit;

			$ret = $this->user->modify($data);
			$this->logop("sys_staff");
			redirect(site_url('users/index'));
		}


		//编辑用户信息
        function edituser($uid)
        {
        	
            $post = $_POST;
            if($post) {
                if ($_POST['pwd'] && !empty($_POST['pwd']) ) {
                    $data['passwd'] = md5($_POST['pwd']);
                }
                //$title0 = $data['title0'];
                if(isset($post['userid']) && !empty($post['userid']) ){
                    $data['id'] = $post['userid'];
                }
                if(isset($post['owner_id']) && !empty($post['owner_id']) ){
                    $data['owner_id'] = $post['owner_id'];
                }
                if(isset($post['datacenter_id']) && !empty($post['datacenter_id']) ){
                    $data['datacenter_id'] = $post['datacenter_id'];
                }
                if(isset($post['role_id']) && !empty($post['role_id']) ){
                    $data['role_id'] = $post['role_id'];
                    $role = $this->db->get_where('sys_group',array('id'=>$data['role_id']))->result_array();
                    if(isset($role[0]['title']))
                        $data['level'] = $role[0]['title'];
                }
                if(isset($post['depart_id']) && !empty($post['depart_id']) ){
                    $data['depart_id'] = $post['depart_id'];
                }
                if(isset($post['code']) && !empty($post['code']) ){
                    $data['code'] = $post['code'];
                }
                if(isset($post['name']) && !empty($post['name']) ){
                    $data['name'] = $post['name'];
                }
                if(isset($post['email']) && !empty($post['email']) ){
                    $data['email'] = $post['email'];
                }
                if(isset($post['qq']) && !empty($post['qq']) ){
                    $data['qq'] = $post['qq'];
                }
                if(isset($post['sex']) && !empty($post['sex']) ){
                    $data['sex'] = $post['sex'];
                }
                if(isset($post['mobile']) && !empty($post['mobile']) ){
                    $data['mobile'] = $post['mobile'];
                }
                if(isset($post['sms_warning_level']) && !empty($post['sms_warning_level']) ){
                    $data['sms_warning_level'] = $post['sms_warning_level'];
                }
                if(isset($post['email_warning_level']) && !empty($post['email_warning_level']) ){
                    $data['email_warning_level'] = $post['email_warning_level'];
                }
                
                $userid = $this->user->modify($data);
                $this->logop("sys_staff");
                if ($userid) {
                	echo '<meta charset="UTF-8" />';
                    echo "<script>alert('更新用户成功!');document.URL=location.href;</script>";
                }else{
                	echo '<meta charset="UTF-8" />';
                	echo "<script>alert('更新用户失败!');history.go(-1);</script>";
                }
                
            }else{
                $data['user'] = $this->user->getById($uid);
                if( empty($data['user']) ){
                	echo '<meta charset="UTF-8" />';
                	echo "$uid<script>alert('用户信息不存在!');history.go(-1);</script>";
                	exit;
                }

                $this->load->model("depart");
                $depart = $this->depart->getDepartName( $data['user']['owner_id'] );
                foreach($depart as $k=>$v){
                    $arr_depart[$k] = $v['name'];
                }
                $data['depart'] = $arr_depart;
                $title = $this->depart->getNameByOwnerId( $data['user']['owner_id'] );
                foreach($title as $k=>$v){
                    $arr_title[$k] = $v['title'];
                }
                $data['title'] =$arr_title;


                $this->load->model("group");
                $this->load->model("datacenter");
                $this->load->model("owner");
                //$data['gs'] = $this->group->getAll2();
				$data['gs'] = $this->group->getAll2($this->_user['role_id']);
                $data['dcs'] = $this->datacenter->getAll2();
                $data['owner'] = $this->owner->getAll2();
                $this->load->helper('form');
                $this->load->view('template/user/edit.html',$data);
            }

        }

        function allocatePermition($uid, $rid)
        { 
            $this->load->model("sysrights");
            $this->sysrights->permitSet($uid,$rid);
        }
         
         //ajax:根据ownerid 查询部门
         function getdepartByownerid()
         {
         	$ownerid = $_REQUEST['ownerid'];
         	if ($ownerid) {
         		 $this->load->model("depart");
	         	 $data['depart'] = $this->depart->getByOwnerId($ownerid);
	         	 echo json_encode($data['depart']);
         	}
         }
         //ajax:根据ownerid 查询职位
         function getNameByownerid()
         {
         	$ownerid = $_REQUEST['ownerid'];
         	if ($ownerid) {
         		$this->load->model("depart");
	         	 $ret = $this->depart->getNameByOwnerId($ownerid);
	         	 echo json_encode( $ret );
         	}
         }
         

         function del()
         {
            if($this->session->userdata['level'])
                return;
           /* $this->db->where('id', $id);
            $this->db->delete("sys_staff");*/
            //$this->db->delete("sys_staff", array("id"=>intval($id)));
         }


        function userinfo()
        {

           $this->load->view('template/user/info.html');
        }

        /**
         * 修改密码
         * @auther xzhang
         */
        function modify()
        {
           /* $user = $this->session->userdata('user');
            echo "<pre>"; var_dump($user);
            exit;*/

            if($_POST){
                echo '<meta charset="utf-8" />';

                $op = $this->input->get_post("oldpwd");
                $user = $this->session->userdata('user');
                if(md5($op) == $user['passwd'])
                {
                    $data['id'] = $user['id'];
                    $data['passwd'] =md5( $this->input->get_post("pwd") );
                    $data['utime'] = date('Y-m-d H:i:s',time());
                    $ret = $this->user->modify($data);
                    $this->logop("sys_staff");
                    if($ret){
                        echo "<script>alert('修改成功,请重新登陆!');</script>";
                        $this->logout();
                    }else{
                        echo "<script>alert('修改失败!');window.location.href='?error=password is wrong!';</script>";
                    }
                }else{
                    echo "<script>alert('旧密码输入不正确!');window.location.href='?error=password is wrong!';</script>";
                }

                exit;
            }
            $this->load->view("template/user/modify.html");
        }
		
        /**
         * 分配工作台默认图标
         *
         * @param unknown_type $userid
         */
        function setDefaultIcon($userid=null)
        {
        	if ($userid!=null) {
        		$this->load->model("dcim_model");
				$ret = $this->dcim_model->setUserDefaultIcon($userid);
        	}
        }
        //ajax:验证邮箱
        function checkemail()
        {
        	$email = $_REQUEST['email'];

            $user = $this->user->getByMail($email);
            if($user && isset($user)){
                die("1");
            }else{
                die("0");
            }
        }
     }
      
?>
